package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bzkj.basicinfo.domain.basic.vo.NccBasicUnitVo;
import com.bzkj.basicinfo.domain.basic.vo.TreeSkuTypeVo;
import com.bzkj.basicinfo.domain.basic.vo.TreeSkuUnitVo;
import com.bzkj.basicinfo.domain.ncc.BasicSkuUnitDetail;
import com.bzkj.basicinfo.domain.ncc.NccBasicDepartment;
import com.bzkj.basicinfo.domain.ncc.NccBasicUnit;
import com.bzkj.basicinfo.mapper.NccBasicSkuMapper;
import com.bzkj.basicinfo.mapper.NccBasicUnitMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicUnitService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wangzhichao
 * @ClassName NccBasicUnitServiceImpl
 * @Date 2024/12/10 11:18:46
 * @description ncc物料单位：3
 */
@Slf4j
@Service("nccBasicUnitServiceImpl")
public class NccBasicUnitServiceImpl implements NccBasicUnitService
{
    @Autowired
    private NccBasicUnitMapper nccBasicUnitMapper;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Autowired
    private HttpClientUtils hcu;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private NccBasicSkuMapper nccBasicSkuMapper;

    /**
     * 查询物料信息
     *
     * @Author wangzhichao
     * @Date 2024/12/10 11:26:19
     */
    @Override
    public List<TreeSkuUnitVo> findNccBasicUnitData(NccBasicUnit entity)
    {
        List<NccBasicUnit> list = nccBasicUnitMapper.findNccBasicUnitData(entity);
        List<BasicSkuUnitDetail> all = nccBasicUnitMapper.findAllNccBasicUnitDetail();
        Map<String, TreeSkuUnitVo> map = new HashMap<>();
        List<TreeSkuUnitVo> collect = list.stream().map(item -> {
            TreeSkuUnitVo temp = new TreeSkuUnitVo();
            BeanUtils.copyProperties(item, temp);
            map.put(temp.getPk_measdoc(), temp);
            return temp;
        }).collect(Collectors.toList());

        all.forEach(item -> {
            TreeSkuUnitVo type = map.get(item.getParentUnitId());
            if (!Objects.isNull(type)) {
                type.setChildrenAdd(item);
            }
        });
        return collect;
    }

    /**
     * 根据code修改物料信息
     *
     * @param entity
     * @Author wangzhichao
     * @Date 2024/12/10 11:43:30
     */
    @Override
    public AjaxResult nccBasicUnitUpdate(NccBasicUnit entity)
    {
        try {
            int i = nccBasicUnitMapper.nccBasicUnitUpdate(entity);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
        } catch(Exception e) {
            log.info("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 新增物料信息
     *
     * @Author wangzhichao
     * @Date 2024/12/10 16:49:25
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicUnitSave(NccBasicUnit entity)
    {
        NccBasicUnit one = nccBasicUnitMapper.getNccBasicUnitOne(entity.getCode());
        if(Objects.isNull(one)) {
            String userName = SecurityUtils.getLoginUser().getUser().getUserName();
            entity.setModifier(userName);
            entity.setCreator(userName);
            entity.setCreateTime(new Date());
            entity.setTs(new Date());
            entity.setPk_org("1001A110000000004AOQ");
            entity.setPk_group("BEITEJITUAN123456789");
            synchronized(this) {
                String measdoc = "WMS" + uniq.generateUniqueIdentifier();
                entity.setPk_measdoc(measdoc);
            }
            try {
                int i = nccBasicUnitMapper.nccBasicUnitSave(entity);
                return AjaxResult.success("新增成功");
            } catch(Exception e) {
                log.error("新增失败:{}", e);
                return AjaxResult.error("新增失败");
            }
        } else {
            return AjaxResult.error("单位代码重复");
        }
    }

    @Override
    public AjaxResult deleteNccBasicUnit(String id) {
        int i = nccBasicUnitMapper.deleteNccBasicUnit(id);
        if(i>0){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    @Override
    public R findNccBasicUnitAll()
    {
        List<NccBasicUnitVo> data = nccBasicUnitMapper.findNccBasicUnitAll();
        return R.ok(data);
    }

    /**
     * 定时任务
     * 定时获取当前数据
     * @param flag 是否定时任务调用
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag)
    {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 3, pkOrgCode);
        String responseBody = response.body();
        JSONObject entries = JSONUtil.parseObj(responseBody);
        JSONArray dataArray = entries.getJSONArray("data");
        List<NccBasicDepartment> nccBasicDepartments = dataArray.toList(NccBasicDepartment.class);
        // 收集rep系统数据
        if(! nccBasicDepartments.isEmpty())
            extracted(nccBasicDepartments);

        return R.ok("同步成功");
    }



    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<NccBasicDepartment> list)
    {
        for (NccBasicDepartment nccBasicDepartment : list) {
            nccBasicUnitMapper.insertOrUpdate(nccBasicDepartment);
        }
    }

}
